package com.example.prison.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.prison.config.AccPushProccesor;
import com.example.prison.config.Response;
import com.example.prison.entity.*;
import com.example.prison.service.*;
import com.example.prison.util.FileUtil;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Api(tags = "A模拟设备测试")
@RestController
@RequestMapping("/api")
public class ZooTestController {

    @Autowired
    private PeopleManageService peopleManageService;
    @Autowired
    private AttendanceListService attendanceListService;
    @Autowired
    private LeaveManagementService leaveManagementService;
    @Autowired
    private SecurityListService securityListService;
    @Autowired
    private UseCarManagementService useCarManagementService;
    @Autowired
    private CarManagementService carManagementService;
    @Autowired
    private CarTrafficRecordService carTrafficRecordService;
    @Autowired
    private DeviceAlarmRecordService deviceAlarmRecordService;
//    @Autowired
//    private EventAlarmRecordService eventAlarmRecordService;
    @Autowired
    private AttendanceDeviceInfoService attendanceDeviceInfoService;
    @Autowired
    private SecurityDeviceInfoService securityDeviceInfoService;
    @Autowired
    private VisitorDeviceInfoService visitorDeviceInfoService;
    @Autowired
    private DeviceManagementService deviceManagementService;
    @Autowired
    private AccPushProccesor accPushProccesor;
    @Autowired
    private VisitorAppointmentService visitorAppointmentService;

    @ApiOperation("隔离仓访客验证测试")
    @PostMapping("/warehouseTest")
    public Response<?> warehouseTest(@Parameter(description = "PID")@RequestParam String pid,
                                     @Parameter(description = "访客预约时间(yyyy-MM-dd)")@RequestParam String time,
                                       @Parameter(description = "访客是否在黑名单（0否1是）")@RequestParam String isBlack,
                                       @Parameter(description = "设备序列号")@RequestParam String SN) {
        VisitorAppointment visitor = visitorAppointmentService.getByPIDAndTime(pid, time);
        if(isBlack == "1") {
            return Response.error("访客在黑名单");
        } else {
            //修改访客状态为3已通过隔离仓检查  0未进场/1已入场/2已通过监狱门岗检查/3已通过隔离仓检查/4已通过值班人员检查/5已出场
            visitor.setVisitorStatus("3");
            if(ObjectUtils.isNotEmpty(deviceManagementService.getOneByNumber(SN))) {
                DeviceManagement device = deviceManagementService.getOneByNumber(SN);
                if(device.getAccess().contains("出")) {
                    visitor.setOutWarehouse(SN);
                } else {
                    visitor.setInWarehouse(SN);
                }
            }
            visitorAppointmentService.update(visitor,visitor.getId());
        }
        return Response.success("考勤打卡测试成功");
    }

    @ApiOperation("访客、人员信息写入cmd.txt")
    @PostMapping("/VPAppendToTXT")
    public Response<?> addSecurityTest() {
        //每新增人员或访客时调用  PID暂时定为手机号
        String filePath = "d://cmd.txt";
        //删除旧文件
        FileUtil.DeleteTxtFile(filePath);
        String cmd = "";
        List<VisitorAppointment> visitorList = visitorAppointmentService.list();
        for(VisitorAppointment visitor : visitorList) {
            //C:123:DATA UPDATE USERINFO PIN=1 Name=1 Pri=0 Passwd=1 Grp=1
            cmd = "C:"+visitor.getPhone()+":DATA UPDATE USERINFO PIN="+visitor.getPhone()+" Name="+visitor.getVisitorName()+" Pri=0 Passwd=1 Grp=1";
            FileUtil.AppendToFile(filePath, cmd);
        }

        List<PeopleManage> peopleList = peopleManageService.list();
        for(PeopleManage people : peopleList) {
            cmd = "C:"+people.getPhone()+":DATA UPDATE USERINFO PIN="+people.getPhone()+" Name="+people.getName()+" Pri=0 Passwd=1 Grp=1";
            FileUtil.AppendToFile(filePath, cmd);
        }
        FileUtil.ReadFile(filePath);
        return Response.success("");
    }


    @ApiOperation("考勤打卡测试")
    @PostMapping("/addAttendanceTest")
    public Response<?> addAttendanceTest(@Parameter(description = "PID打卡工号/姓名")@RequestParam String id,
                                         @Parameter(description = "考勤打卡时间(yyyy-MM-dd HH:mm:ss)")@RequestParam String time,
                                         @Parameter(description = "设备序列号")@RequestParam String SN) {
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
        //添加考勤记录
        AttendanceList attendanceList = new AttendanceList();
        attendanceList.setRecordId(0);
        attendanceList.setId(id);
        attendanceList.setTime(time);
        attendanceList.setSn(SN);
        attendanceListService.addAttendanceRecord(attendanceList);
        AttendanceDeviceInfo device = attendanceDeviceInfoService.getOneByNumber(SN);
        if(ObjectUtils.isNotEmpty(leaveManagementService.getLeavesByNameAndStatus(id,"未销假")) && Objects.equals(device.getAccess(), "进")) {
            //若进入营区人员为请假人员，则修改请假状态为已销假,修改人员状态为营区内
            List<LeaveManagement> leaves = leaveManagementService.getLeavesByNameAndStatus(id,"未销假");
            for (LeaveManagement leave : leaves) {
                leave.setStatus("已销假");
                leaveManagementService.endLeave(leave);
            }
            List<PeopleManage> list = peopleManageService.getByStatusAndName(id, "营区外");
            for (PeopleManage personnel : list) {
                personnel.setStatus("营区内");
                peopleManageService.update(personnel, personnel.getId());
            }
        } else if(ObjectUtils.isNotEmpty(leaveManagementService.getLeavesByNameAndStatus(id,"同意")) && Objects.equals(device.getAccess(), "出")) {
            //若离开营区人员为请假人员，则修改请假状态为未销假,修改人员状态为营区外
            List<LeaveManagement> leaves = leaveManagementService.getLeavesByNameAndStatus(id,"同意");
            for (LeaveManagement leave : leaves) {
                if(date.compareTo(leave.getBeginDate()) >= 0) {
                    leave.setStatus("未销假");
                    leaveManagementService.updateStatus(leave);
                }
            }
            List<PeopleManage> list = peopleManageService.getByStatusAndName(id,"营区内");
            for (PeopleManage personnel : list) {
                personnel.setStatus("营区外");
                peopleManageService.update(personnel, personnel.getId());
            }
        } else if(ObjectUtils.isNotEmpty(peopleManageService.getByStatusAndName(id,"营区内")) && Objects.equals(device.getAccess(), "出") && !ObjectUtils.isNotEmpty(leaveManagementService.getLeavesByNameAndStatus(id,"同意"))) {
            //人员离开营区且非请假人员，修改人员状态为营区外
            List<PeopleManage> list = peopleManageService.getByStatusAndName(id,"营区内");
            for (PeopleManage personnel : list) {
                personnel.setStatus("营区外");
                peopleManageService.update(personnel, personnel.getId());
            }
        } else if(ObjectUtils.isNotEmpty(peopleManageService.getByStatusAndName(id,"营区内")) && Objects.equals(device.getAccess(), "进")) {
            //人员进入营区，修改人员状态为营区内
            List<PeopleManage> list = peopleManageService.getByStatusAndName(id,"营区内");
            for (PeopleManage personnel : list) {
                personnel.setStatus("营区内");
                peopleManageService.update(personnel, personnel.getId());
            }
        }
        return Response.success("考勤打卡测试成功");
    }

    @ApiOperation("安防打卡测试")
    @PostMapping("/addSecurityTest")
    public Response<?> addSecurityTest(@Parameter(description = "PID打卡工号/姓名")@RequestParam String pin,
                                       @Parameter(description = "安防打卡时间(yyyy-MM-dd HH:mm:ss)")@RequestParam String time,
                                       @Parameter(description = "设备序列号")@RequestParam String SN) {
        //添加安防记录
        SecurityList securityList = new SecurityList();
        securityList.setRecordId(0);
        securityList.setPin(pin);
        securityList.setTime(time);
        securityList.setSn(SN);
//            securityList.setAddress(securityDeviceInfoService.getOneByNumber(SN).getDeviceArea());
        securityListService.addSecurityRecord(securityList);
        return Response.success("考勤打卡测试成功");
    }

    @ApiOperation("考勤/安防设备心跳测试")
    @PostMapping("/heatTest")
    public Response<?> heatTest(@Parameter(description = "设备序列号")@RequestParam String SN) {
        accPushProccesor.heartbeat(SN);
        return Response.success("考勤/安防设备心跳测试成功");
    }

    @ApiOperation("车辆通行测试")
    @PostMapping("addCarTrafficTest")
    public Response<?> addCarTrafficTest(@Parameter(description = "车牌号")@RequestParam String license,
                                         @Parameter(description = "设备序列号")@RequestParam String serialno) {
        //车辆数据记录
        CarTrafficRecord record = new CarTrafficRecord();
        record.setNumber(license);
        record.setSn(serialno);
        record.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if(ObjectUtils.isNotEmpty(attendanceDeviceInfoService.getOneByNumber(license))) {
            AttendanceDeviceInfo device = attendanceDeviceInfoService.getOneByNumber(license);
            record.setDescribe(device.getAccess());
        }
        carTrafficRecordService.add(record);
        AttendanceDeviceInfo device = attendanceDeviceInfoService.getOneByNumber(serialno);
        if(ObjectUtils.isNotEmpty(useCarManagementService.getOneByNumberAndUseStatus(license,"使用中")) && Objects.equals(device.getAccess(), "进")) {
            //若进入营区车辆为用车申请中车辆，则修改使用状态为已返回
            UseCarManagement useCar = useCarManagementService.getOneByNumberAndUseStatus(license,"使用中");
            useCar.setUseStatus("已返回");
            useCarManagementService.update(useCar,useCar.getId());
        } else if(ObjectUtils.isNotEmpty(useCarManagementService.getOneByNumberAndUseStatus(license,"未出发")) && Objects.equals(device.getAccess(), "出")) {
            //若离开营区车辆为用车申请中车辆，则修改使用状态为用车中
            UseCarManagement useCar = useCarManagementService.getOneByNumberAndUseStatus(license,"未出发");
            useCar.setUseStatus("用车中");
            useCarManagementService.update(useCar,useCar.getId());
        } else if(ObjectUtils.isNotEmpty(carManagementService.getOneByNumber(license)) && Objects.equals(device.getAccess(), "出")) {
            //车辆离开营区，修改车辆状态为营区外
            CarManagement car = carManagementService.getOneByNumber(license);
            car.setCarStatus("营区外");
            carManagementService.update(car,car.getCarId());
        } else if(ObjectUtils.isNotEmpty(carManagementService.getOneByNumber(license)) && Objects.equals(device.getAccess(), "进")) {
            //车辆进入营区，修改车辆状态为营区内
            CarManagement car = carManagementService.getOneByNumber(license);
            car.setCarStatus("营区内");
            carManagementService.update(car,car.getCarId());
        }
        return Response.success("车辆识别测试成功");
    }

    @ApiOperation("设备告警测试")
    @PostMapping("addDeviceAlarmTest")
    public Response<?> addDeviceAlarmTest(@Parameter(description = "设备序列号")@RequestParam String SN,
                                          @Parameter(description = "告警时间(yyyy-MM-dd HH:mm)")@RequestParam String time) {
        //设备告警记录
        DeviceAlarmRecord record = new DeviceAlarmRecord();
        record.setSn(SN);
        record.setAlarmLevel("设备告警");
        record.setTime(time);
        record.setAddress("--");
        if(ObjectUtils.isNotEmpty(attendanceDeviceInfoService.getOneByNumber(SN))) {
            AttendanceDeviceInfo device = attendanceDeviceInfoService.getOneByNumber(SN);
            record.setAddress(device.getDeviceArea());
        }
        if(ObjectUtils.isNotEmpty(securityDeviceInfoService.getOneByNumber(SN))) {
            SecurityDeviceInfo device = securityDeviceInfoService.getOneByNumber(SN);
            record.setAddress(device.getDeviceArea());
        }
        if(ObjectUtils.isNotEmpty(visitorDeviceInfoService.getOneByNumber(SN))) {
            VisitorDeviceInfo device = visitorDeviceInfoService.getOneByNumber(SN);
            record.setAddress(device.getDeviceArea());
        }
        deviceAlarmRecordService.add(record);
        return Response.success("设备告警测试成功");
    }
//
//    @ApiOperation("事件告警测试")
//    @PostMapping("addEventAlarmTest")
//    public Response<?> addEventAlarmTest(@Parameter(description = "事件告警类型（消防/应急/特勤）")@RequestParam String type,
//                                         @Parameter(description = "告警时间(yyyy-MM-dd HH:mm)")@RequestParam String time) {
//        //事件告警记录
//        EventAlarmRecord record = new EventAlarmRecord();
//        record.setSn("--");
//        record.setAddress("--");
//        record.setAlarmLevel(type);
//        record.setTime(time);
//        eventAlarmRecordService.add(record);
//        return Response.success("事件告警测试成功");
//    }
//
//    @SneakyThrows
//    @ApiOperation("特殊车辆直接通行测试")
//    @PostMapping("specialCarPassageTest")
//    public Response<?> specialCarPassageTest(@Parameter(description = "酒精检测结果")@RequestParam Integer result,
//                                             @Parameter(description = "车牌号")@RequestParam String number) {
//        String message = "非特殊车辆";
//        ArrayList<String> carLines = new ArrayList<>();
//            String fileName = "D:\\carNumber.txt";
//            // 带缓冲的流读取，默认缓冲区8k
//        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(fileName), StandardCharsets.UTF_8);
//        BufferedReader reader = new BufferedReader(inputStreamReader);
//            String line;
//            while ((line = reader.readLine()) != null) {
//                carLines.add(line);
//            }
//            //System.out.println(carLines);
//            for(String car : carLines) {
//                if(Objects.equals(car, number) && result == 1) {
//                    message = "特殊车辆直接通行";
//                }
//            }
//
//        return Response.success("特殊车辆直接通行测试",message);
//    }

    @ApiOperation("解析车辆识别json")
    @PostMapping("analysisJson")
    public Response<?> analysisJson(@Parameter(description = "车辆识别json")@RequestBody String jsonData) {
        JsonParser parser = new JsonParser();  //创建JSON解析器
        String number = "";
        do {
            JsonObject jsonObject = (JsonObject) parser.parse(jsonData.toString());
            if (jsonObject == null || jsonObject.isJsonNull()) {
                break;
            }

            // 解析AlarmInfoPlate
            JsonObject jsonAlarmInfoPlate = jsonObject.get("AlarmInfoPlate").getAsJsonObject();
            if (jsonAlarmInfoPlate == null || jsonAlarmInfoPlate.isJsonNull()) {
                break;
            }
            // 获取设备序列号
            String serialno = jsonAlarmInfoPlate.get("serialno").getAsString();
            if (serialno == null || serialno == "") {
                break;
            }
            number = serialno;
        } while (false);
        return Response.success("解析车辆识别json","设备序列号:"+number);
    }

}
